package com.guanghua.brick.util;

import java.util.HashMap;
import java.util.Map;

/**
 * Iconfig 的 默认实现类
 * 一个Common config对应xml中的一个节点
 * @author leeon
 */
public class CommonConfig implements IConfig {
	private String name = null;

	private String text = null;

	private HashMap<String, String> attributes = new HashMap<String, String>();

	private HashMap<String, IConfig[]> childrenList = new HashMap<String, IConfig[]>();

	
	/**
	 * 获取界面名称
	 */
	public String getName() {
		return this.name;
	}

	/**
	 * 获取节点的text值，包括cdata的值
	 */
	public String getText() {
		return this.text;
	}

	
	/**
	 * 获取名字为tagName的子节点的text的值，包括cdata的值
	 */
	public String getText(String tagName) {
		if (this.getChildren(tagName) == null) {
			return null;
		} else {
			return this.getChildren(tagName)[0].getText();
		}
	}

	/**
	 * 根据节点属性名称获取属性值
	 */
	public String getAttribute(String attributeName) {
		if (this.attributes.get(attributeName) == null) {
			return null;
		} else {
			return this.attributes.get(attributeName).toString();
		}
	}

	/**
	 * 获取该节点下所有名字为childname的子节点
	 */
	public IConfig[] getChildren(String childName) {
		Object children = this.childrenList.get(childName);

		if (children != null) {
			return (IConfig[]) children;
		} else {
			return null;
		}
	}
	
	/**
	 * 设定节点名称
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * 设点节点text值
	 */
	public void setText(String text) {
		this.text = text;
	}
	
	/**
	 * 设定节点上某个属性的值
	 */
	public void setAttribute(String attributeName, String attributeValue) {
		this.attributes.put(attributeName, attributeValue);
	}
	
	/**
	 * 设定该节点的某个子节点
	 */
	public void setChild(IConfig child) {
		if (child != null) {
			String childName = child.getName();
			IConfig[] children = this.getChildren(childName);

			if (children == null) {
				this.childrenList.put(childName, new IConfig[] { child });
			} else {
				IConfig[] newChildren = new IConfig[children.length + 1];

				for (int i = 0; i < children.length; i++) {
					newChildren[i] = children[i];
				}

				newChildren[children.length] = child;

				this.childrenList.put(childName, newChildren);
			}
		}
	}

	/**
	 * 替换该节点的某个子节点
	 */
	public void replaceChild(IConfig child) {
		if (child != null) {
			String childName = child.getName();
			IConfig[] children = this.getChildren(childName);

			if (children == null) {
				this.childrenList.put(childName, new IConfig[] { child });
			} else {
				IConfig[] newChildren = new IConfig[1];
				newChildren[0] = child;
				this.childrenList.put(childName, newChildren);
			}
		}
	}
	
	/**
	 * 以map的形式返回属性map
	 */
	public Map<String, String> getAttributeMap() {
		return this.attributes;
	}

}
